package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.util.POIUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 小樱
 * @version 1.0
 * @date 2023/4/27 11:03
 * @Description 预约设置Controller
 */
@RestController
@Slf4j
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 根据月份查询数据
     *
     * @param year  年
     * @param month 月
     * @return
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam Integer year, @RequestParam Integer month) {
        //查询
        List<Map<String, Object>> dataList = orderSettingService.getOrderSettingByMonth(year, month);

        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS, dataList);
    }

    /**
     * 根据日期编辑
     *
     * @param orderSetting
     * @return
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) throws ParseException {
        orderSettingService.editNumberByDate(orderSetting);
        return new Result(true, MessageConst.ORDERSETTING_SUCCESS);
    }


    /**
     * 完成上传excel批量预约并保存到数据库
     * @param multipartFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile) {
        log.info("上传的是fileName:{},size:{}", multipartFile.getOriginalFilename(), multipartFile.getSize());
        String filename = multipartFile.getOriginalFilename();
        if(StringUtils.isEmpty(filename)){
            return new Result(false,"缺少文件名");
        }
        //1 提期excel数据
        Workbook workbook = null;
        try (InputStream is = multipartFile.getInputStream();) {
            //1.1构造workbook
            if(filename.endsWith(".xls")){
                workbook = new HSSFWorkbook(is);
            }else if(filename.endsWith(".xlsx")){
                workbook = new XSSFWorkbook(is);
            }else{
                return new Result(false,MessageConst.ACTION_FAIL);
            }
        } catch (IOException e) {
            log.error("",e);
            return new Result(false, MessageConst.ACTION_FAIL);
        }
        //1.2遍历取数据
        List<OrderSetting> orderSettings = new ArrayList<>();
        for (Sheet sheet : workbook) {
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                OrderSetting orderSetting = parseOrderSetting(row);
                orderSettings.add(orderSetting);
            }
        }
        //插入数据库
        orderSettingService.xinzeng(orderSettings);
        return new Result(true,MessageConst.IMPORT_ORDERSETTING_SUCCESS);
    }
    /**
     * 从excel行提取OrderSetting数据
     * @param row
     * @return
     */
    private OrderSetting parseOrderSetting(Row row){
        Date date = null;
        Integer number = null;
        try {
            //获取日期
            if(null != row.getCell(0) ){
                //如果单元格没有数据，则getDateCellValue返回null
                date = row.getCell(0).getDateCellValue();
            }
            //获取最大预约数量
            if(null != row.getCell(1)){
                //如果单元格没有数据，则getNumericCellValue返回0
                double numberValue = row.getCell(1).getNumericCellValue();
                //将double型转为int型
                number =  Double.valueOf(numberValue).intValue();
            }
        }catch (IllegalStateException|NumberFormatException e){
            log.error("",e);
            throw new BusinessRuntimeException(String.format("数据格式错误,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }
        // 判断是否缺少数据
        if(null == date || null == number){
            throw new BusinessRuntimeException(String.format("缺少必填数据,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }
        return new OrderSetting(date,number);
    }

}